import React,{Component} from 'react';
import './comment.less'
class Comment extends Component{
  constructor(props){
      super(props);
      this.state={
        timeString:""
      }
  }
  _updateTimeString(){
    let duration  = parseInt((new Date().getTime()-this.props.commentContent.createdTime)/1000)+1;
    let timeString = "";
    if(duration<60){
        timeString = parseInt(duration)+"秒前";
    }else if(60<=duration&&duration<3600){
      timeString = parseInt(duration/60)+"分钟前";
    }else if(3600<=duration&&duration<3600*24){
      timeString = parseInt(duration/3600)+"小时前";
    }else if(3600*24<=duration){
      timeString = parseInt(duration/(3600*24))+"天前";
    }
    this.setState({
        timeString:timeString
    });
  }
  handleDelete(){
    this.props.onDeleteComment(this.props.commentContent);
  }
  _getProcessedContent (content) {
   return content.replace(/&/g, "&amp;")
      .replace(/</g, "&lt;")
      .replace(/>/g, "&gt;")
      .replace(/"/g, "&quot;")
      .replace(/'/g, "&#039;")
     .replace(/`([\S\s]+?)`/g, '<code>$1</code>')
 }
  componentWillMount(){
    this._updateTimeString();
    this.timer = setInterval(()=>{
        this._updateTimeString();
    },5000);
  }
  componentWillUnmount(){
    clearInterval(this.timer);
  }
  render(){
    return(
      <div className="comment-group">
          <div className="comment-username">{this.props.commentContent.name}：</div>
          <div className="comment-content" dangerouslySetInnerHTML={{
  __html: this._getProcessedContent(this.props.commentContent.content)
}} />
          <div>{this.state.timeString}</div>
          <span className='comment-delete' onClick={this.handleDelete.bind(this)}>删除</span>
      </div>
    )
  }
}
export default Comment
